package thread;

import java.util.Random;


//计算奇偶分别的和
class SumCalculator implements Runnable {
    private final int[] numbers;
    private final int startIndex;
    private int sum;

    public SumCalculator(int[] numbers, int startIndex) {
        this.numbers = numbers;
        this.startIndex = startIndex;
        this.sum = 0;
    }

    @Override
    public void run() {
        for (int i = startIndex; i < numbers.length; i += 2) {
            sum += numbers[i];
        }
    }

    public int getSum() {
        return sum;
    }
}

public class MultiThreadedArrayum {
    public static void main(String[] args) throws InterruptedException {
        int arrayLength = 10_000_000;//1千万

        int[] nums = new int[arrayLength];

        Random random = new Random();//随机生成数
        for (int i = 0; i < arrayLength; i++) {
            nums[i] = random.nextInt(100)+1;//随机生成1-100之间的随机数
        }

        SumCalculator oddnumber = new SumCalculator(nums,1);//奇数
        SumCalculator evennumber = new SumCalculator(nums,0);//偶数

        //记录开始时间
        long starttime = System.currentTimeMillis();

        //创建并启动线程
        Thread odd = new Thread(oddnumber);
        Thread even = new Thread(evennumber);
        odd.start();
        even.start();

        //等待线程完成
        even.join();
        odd.join();

        //汇总和
        int sums = oddnumber.getSum()+ evennumber.getSum();

        //记录结束时间
        long lasttime = System.currentTimeMillis();
        long times = lasttime-starttime;

        // 输出结果
        System.out.println("总和: " + sums);
        System.out.println("执行时间: " + times + "毫秒");

    }
}
